const express = require('express')
const addDataModel = require('../model/addDataModel')
const userDataModel = require('../model/userDataModel')
const vipUserModel = require('../model/vipUserModel')
const ifToken = require('../utils/token')
const router = express.Router()

//获取推荐数据
router.get('/getData', async (req, res) => {
    const data = await addDataModel.aggregate([
        { $sample: { size: 6 } }
    ])
    res.json({ code: '200', data })
})

//随机6条数据
router.get('/getSimpleData', async (req, res) => {
    const data = await addDataModel.aggregate([
        { $sample: { size: 6 } }
    ])
    res.json({ code: '200', data })
})

//指定数据
router.post('/getIdData', async (req, res) => {
    const {_id} = req.body
    const data = await addDataModel.findOne({_id})
    res.json({ code: '200', data })
})

//获取全部数据
router.post('/getFindData', async (req, res) => {
    const data = await addDataModel.find()
    res.json({ code: '200', data })
})


//添加数据
router.post('/addData',ifToken, async (req, res) => {
    const { title, text, money, userid, date } = req.body
    const userMail = await userDataModel.findOne({_id:userid})
    const vip = await vipUserModel.findOne({mail:userMail.mail})
    if(!vip) return res.json({ code: '305', msg: '请开通会员在进行发布' })
    try {
        const data = await userDataModel.findOne({_id:userid})
        await addDataModel.create({ title, text, money, userid, date,userName:data.name })
        res.json({ code: '200', msg: '添加数据成功' })
    } catch (err) {
        res.json({ code: '304', msg: err })
    }
})

//模糊查询
router.post('/searchData', async (req, res) => {
    const { input,input2 } = req.body
    const data = await addDataModel.find({ money: { $gte: input, $lte: input2 } })
    res.json({ code: '200', data })
})

module.exports = router